<template>
	<view class="cart">
		<view class="cart-box" v-if="cart.length !== 0">
			<myAddress></myAddress>
			<view class="cart-title">
				<uni-icons type="shop"></uni-icons>
				<text>购物车</text>
			</view>
			<!-- 商品列表区域 -->
			<uni-swipe-action>
				<block v-for="(item, i) in cart" :key="i">
					<!-- 滑动删除效果 -->
					<uni-swipe-action-item :right-options="options" @click="swipeActionClickHandler(item)">
						<myGoods :goods="item" :showRadio="true" @radio-change="changeCartState" :showNum="true"
							@num-change="updateNum"></myGoods>
					</uni-swipe-action-item>
				</block>
			</uni-swipe-action>
			<view class="account-box">
				<myAccount></myAccount>
			</view>
		</view>
		<!-- 购物车为空的时候 -->
		<view class="empty-cart" v-else>
			<image src="/static/cart_empty@2x.png" class="empty-img"></image>
			<text class="tip-text">空空如也~</text>
		</view>
	</view>
</template>

<script>
	// 按需导入 mapGetters 这个辅助方法
	import {
		mapGetters,
		mapState,
		mapMutations
	} from 'vuex'
	import myGoods from '@/components/my_goods/my_goods.vue'
	// 导入自己封装的 mixin 模块
	import badgeMix from '@/mixins/tabbar-badge.js'
	import myAddress from '@/components/my_address/my_address.vue'
	import myAccount from '@/components/my_account/my_account.vue'

	export default {
		data() {
			return {
				options: [{
					text: '删除', // 显示的文本内容
					style: {
						backgroundColor: '#C00000' // 按钮的背景颜色
					}
				}]
			};
		},

		components: {
			myGoods,
			myAddress,
			myAccount
		},

		// 将 badgeMix 混入到当前的页面中进行使用
		mixins: [badgeMix],
		computed: {
			// 将 m_cart 模块中的 total 映射为当前页面的计算属性
			...mapGetters('m_cart', ['total']),
			...mapState('m_cart', ['cart'])
		},

		onShow() {
			// 在页面刚展示的时候，设置数字徽标
			this.setBadge()
		},

		methods: {
			setBadge() {
				// 调用 uni.setTabBarBadge() 方法，为购物车设置右上角的徽标
				uni.setTabBarBadge({
					index: 2, // 索引
					text: this.total + '' // 注意：text 的值必须是字符串，不能是数字
				})
			},

			...mapMutations('m_cart', ['updateCartState', 'updateCartCount', 'deleteGoods']),

			changeCartState(e) {
				this.updateCartState(e)
			},

			updateNum(e) {
				this.updateCartCount(e)
			},

			swipeActionClickHandler(e) {
				this.deleteGoods(e.goods_id)
				this.setBadge()
			}
		}
	}
</script>

<style lang="scss">
	.cart-title {
		height: 40px;
		display: flex;
		font-size: 12px;
		padding-left: 5px;
		align-items: center;

		text {
			margin-left: 5px;
		}
	}

	uni-swipe-action-item {
		.button-group--right {
			background-color: rgb(244, 154, 193);
			box-shadow: 5px 5px 5px rgba(0, 0, 0, .3);
		}
	}
	
	.empty-cart {
	  display: flex;
	  flex-direction: column;
	  align-items: center;
	  padding-top: 150px;
	
	  .empty-img {
	    width: 90px;
	    height: 90px;
	  }
	
	  .tip-text {
	    font-size: 12px;
	    color: gray;
	    margin-top: 15px;
	  }
	}
</style>
